<template>
	<view id='select_address_container'>
		<!-- 页面标题 -->
		
		<!-- 表单区域 -->
		<view class="form-container">
			<form @submit="saveAddress">
				<!-- 姓名输入框 -->
				<view class="form-item">
					<text class="label">收货人</text>
					<input type="text" v-model="formData.name" placeholder="请输入姓名" class="input" />
				</view>
				
				<!-- 电话输入框 -->
				<view class="form-item">
					<text class="label">手机号码</text>
					<input type="number" v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" class="input" />
				</view>
				
				<!-- 省市区选择 -->
				<view class="form-item" @click="openCityPicker">
					<text class="label">所在地区</text>
					<view class="region-picker">
						<text v-if="!formData.region" class="placeholder">请选择所在地区</text>
						<text v-else class="region-text">{{ formData.region }}</text>
						<text class="arrow">></text>
					</view>
				</view>
				
				<!-- 详细地址输入框 -->
				<view class="form-item">
					<text class="label">详细地址</text>
					<textarea v-model="formData.address" placeholder="请输入详细地址：如道路、小区、楼栋号、单元室等" class="textarea" />
				</view>
				
				<!-- 邮政编码输入框 -->
				<view class="form-item">
					<text class="label">邮政编码</text>
					<input type="number" v-model="formData.zipCode" placeholder="请输入邮政编码" maxlength="6" class="input" />
				</view>
				
				<!-- 设为默认地址 -->
				<view class="form-item switch-item">
					<text class="label">设为默认地址</text>
					<switch @change="changeDefaultBtn" v-model="formData.isDefault" color="#FF6A00" />
				</view>
				
				<!-- 保存按钮 -->
				<view class="btn-container">
					<button class="save-btn" form-type="submit">保存收货地址</button>
				</view>
			</form>
		</view>
		
		<!-- 城市选择器组件 -->
		<cityPicker 
			:column="column" 
			:default-value="defaultValue" 
			:mask-close-able="maskCloseAble" 
			@confirm="confirm" 
			@cancel="cancel" 
			:visible="visible"
		/>
	</view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app"
import {ref, reactive, onMounted} from 'vue';
import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker'

onLoad((options)=>{
	/*
		接收操作参数，识别新增还是编辑
		编辑状态下：将数据从localstorage中填上。
		点击保存时如果为编辑状态下，执行更新操作
	*/
   if(options.ops == "edit"){
	   editState.value = true;
	   // 渲染需要编辑的数据
	   showEditeAddressInfo();
	   
	   // 动态修改顶部标题
	   uni.setNavigationBarTitle({
	   	title: "修改收货地址"
	   })
   }
})

// 处理默认切换开关的选择
function changeDefaultBtn(e){
	formData.isDefault = e.detail.value;
}

// 将需要编辑的数据填充到表单上
function showEditeAddressInfo(){
	let editAddressInfo = uni.getStorageSync("editAddressInfo");
	formData.name = editAddressInfo.user_name;
	formData.phone = editAddressInfo.tel_number;
	formData.province = editAddressInfo.province_name;
	formData.city = editAddressInfo.city_name;
	formData.area = editAddressInfo.county_name;
	formData.address = editAddressInfo.detail_info;
	formData.zipCode = editAddressInfo.postal_code;
	// 拼接回显省市区文本
	formData.region = `${editAddressInfo.province_name}${editAddressInfo.city_name}${editAddressInfo.county_name}` 
	formData["id"] = editAddressInfo.id;
	
	// console.log(formData.region);
	
	// console.log(editAddressInfo, "----");
}

// 表示编辑状态
let editState = ref(false);

// 省市区选择器配置
let column = ref(3);  // 3-省市区 2-省市
let defaultValue = ref("420103"); // 默认显示地区编码或名称
let maskCloseAble = ref(true); // 点击模态框是否关闭弹框
let visible = ref(false); // 控制选择器显示和隐藏

// 表单数据对象
const formData = reactive({
  name: '',
  phone: '',
  region: '', // 显示的省市区文本
  province: '', // 省份
  city: '', // 城市
  area: '', // 区域
  provinceCode: '', // 省份编码
  cityCode: '', // 城市编码
  areaCode: '', // 区域编码
  address: '', // 详细地址
  zipCode: '', // 邮政编码
  isDefault: false // 是否默认地址
});

// 打开城市选择器
function openCityPicker() {
  visible.value = true;
}

// 确认选择省市区
function confirm(val) {
  // console.log("===>", val);
  // 更新表单数据
  formData.region = val.name;
  formData.province = val.provinceName;
  formData.city = val.cityName;
  formData.area = val.areaName;
  formData.provinceCode = val.provinceCode || '';
  formData.cityCode = val.cityCode || '';
  formData.areaCode = val.code;
  visible.value = false;
}

// 取消选择
function cancel() {
  visible.value = false;
}

// 保存地址表单
function saveAddress() {
	// 表单验证
	if (!formData.name.trim()) {
		uni.showToast({ title: '请输入收货人姓名', icon: 'none' });
		return;
	}
	
	if (!formData.phone.trim() || !/^1[3-9]\d{9}$/.test(formData.phone)) {
		uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
		return;
	}
	
	if (!formData.region) {
		uni.showToast({ title: '请选择所在地区', icon: 'none' });
		return;
	}
	
	if (!formData.address.trim()) {
		uni.showToast({ title: '请输入详细地址', icon: 'none' });
		return;
	}
	
	if (formData.zipCode && !/^\d{6}$/.test(formData.zipCode)) {
		uni.showToast({ title: '请输入正确的邮政编码', icon: 'none' });
		return;
	}
	
	// 将用户Id添加到表单参数中
	formData["userId"] = uni.getStorageSync("userInfo").user_id;
	
	// 提交数据到服务器
	uni.showLoading({ title: '保存中...' });
	// 分发新增或修改
	if(editState.value){
		// console.log("编辑执行===>");
		execEdite();
		return 1;
	}
	execSave();

}

// 执行收货地址的修改：为了方便-后端先删除后新增
async function execEdite(){
	let userInfo = await uni.getStorageSync("userInfo");
	let res = await uni.$http.put(`/address/edit/${formData.id}/${userInfo.user_id}`, formData);
	
	// 处理提示
	uni.hideLoading();
	uni.$showT(res.data.msg);
	
	if(res.data.code == 0){
		return 0;
	}
	
	// 新增成功，返回上一页
	uni.navigateBack()
}

// 执行收货地址的添加
async function execSave(){
	let res = await uni.$http.post("/user/addAddress", formData);
	uni.hideLoading();
	uni.$showT(res.data.msg);
	
	if(res.data.code == 0){
		return 0;
	}
	
	uni.navigateBack()
	
}

// 如果从编辑页面进入，可以获取地址数据并填充表单
onMounted(() => {
  // 获取页面传参，这里模拟从其他页面传入的地址数据
  const addressId = uni.getStorageSync('edit_address_id');
  if (addressId) {
    // 模拟获取地址数据
    // 实际项目中应该从API获取数据
    setTimeout(() => {
      // 模拟数据，实际项目中应该从服务器获取
      const addressData = {
        id: '1001',
        name: '张三',
        phone: '13800138000',
        province: '湖北省',
        city: '武汉市',
        area: '江汉区',
        address: '解放大道1277号',
        zipCode: '430022',
        isDefault: true
      };
      
      // 填充表单数据
      formData.name = addressData.name;
      formData.phone = addressData.phone;
      formData.region = addressData.province + addressData.city + addressData.area;
      formData.province = addressData.province;
      formData.city = addressData.city;
      formData.area = addressData.area;
      formData.address = addressData.address;
      formData.zipCode = addressData.zipCode;
      formData.isDefault = addressData.isDefault;
      
    }, 500);
  }
});
</script> 

<style lang='scss' scoped>
#select_address_container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
}

.page-header {
  padding: 30rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #eaeaea;
  
  .page-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}

.form-container {
  padding: 20rpx;
  
  .form-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    background-color: #ffffff;
    margin-bottom: 2rpx;
    position: relative;
    
    &:after {
      content: '';
      position: absolute;
      left: 30rpx;
      right: 0;
      bottom: 0;
      height: 1px;
      background-color: #f5f5f5;
    }
    
    .label {
      width: 180rpx;
      font-size: 30rpx;
      color: #333;
      font-weight: 500;
    }
    
    .input {
      flex: 1;
      height: 60rpx;
      font-size: 30rpx;
      color: #333;
    }
    
    .textarea {
      flex: 1;
      height: 120rpx;
      font-size: 30rpx;
      color: #333;
    }
    
    .placeholder {
      color: #999;
    }
    
    .region-picker {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .region-text {
        font-size: 30rpx;
        color: #333;
      }
      
      .arrow {
        font-size: 32rpx;
        color: #ccc;
        transform: rotate(90deg);
        margin-left: 10rpx;
      }
    }
    
    &.switch-item {
      justify-content: space-between;
    }
  }
  
  .btn-container {
    padding: 60rpx 30rpx;
    
    .save-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      background: linear-gradient(to right, #ff8400, #ff6a00);
      color: #ffffff;
      font-size: 32rpx;
      font-weight: 500;
      border-radius: 45rpx;
      text-align: center;
      border: none;
      
      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>